var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op
var db = require('../models')
/* GET users listing. */
router.get('/', async function (req, res, next) {
    try {
        if (req.query.username) {
            var username = req.query.username
            var users = await models.Login.findAll({
                where: { [Op.and]: [{ username: `${username}` }] },
                include: {
                    model: models.User
                }
            })
            res.json({ loginUsers: users })
        } else if (req.query.userId) {
            var userId = req.query.userId
            var user = await models.Login.findOne({
                where: { [Op.and]: [{ userId }] },
                include: {
                    model: models.User
                }
            })
            res.json({ loginUser: user })
        } else {
            var users = await models.Login.findAll({
                include: {
                    model: models.User
                }
            })
            res.json({ loginUsers: users })
        }
    } catch (e) {
        console.log(e);
    }
    // res.send('ok');
});

// 获取用户提交的信息并插入数据库
router.post('/', async function (req, res, next) {
    const { username, password, roleId, userId } = JSON.parse(req.query.data)
    try {
        var user = await models.Login.create({
            username, password, roleId, userId
        })
        res.json({ user })
    } catch (e) {
        console.log(e)
    }
})

// 修改登录信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { username, password, roleId, userId } = JSON.parse(req.query.data)
    try {
        var user = await models.Login.update({
            username, password, roleId, userId
        }, { where: { id } })
        res.json({ user })
    } catch (e) {
        console.log(e)
    }
})


// 删除信息
router.delete('/', async function (req, res, next) {
    const userId = JSON.parse(req.query.userId)
    const t = await db.sequelize.transaction();
    try {
        var loginUser = await models.Login.findOne({
            where: { [Op.and]: [{ userId }] }
        })
        await t.commit()
        if (loginUser) {
            loginUser.destroy()
            res.json({ msg: '删除成功' })
        } else {
            res.json({ msg: '不存在该数据' })
        }
    } catch (error) {
        console.log(error);
        await t.rollback()
    }
})

module.exports = router;
